package com.qzyh.esb.egsa.controller;

import com.qzyh.esb.egsa.bean.vo.MenuTreeVO;
import com.qzyh.esb.egsa.bean.vo.UserMenuTreeVO;
import com.qzyh.esb.egsa.entity.Menu;
import com.qzyh.esb.egsa.service.IMenuService;
import com.qzyh.esb.egsa.utils.FillUtil;
import com.qzyh.esb.egsa.utils.ResultObject;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author whq
 * @since 2023-03-17
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    private static final Logger logger = LoggerFactory.getLogger(MenuController.class);

    @Autowired
    private IMenuService menuService;

    @GetMapping("/list")
    @ApiOperation(value = "查询菜单列表")
    @ApiResponses(value = {@ApiResponse(code = 1, message = "系统繁忙，请稍后重试")})
    public ResultObject<List<MenuTreeVO>> index(@ApiParam(value = "菜单名称") @RequestParam(value="menuName",required=false) String menuName) {
        List<MenuTreeVO> menuTreeVOList = menuService.getList(menuName);
        return ResultObject.success(menuTreeVOList);
    }

    @GetMapping("/superior")
    @ApiOperation(value = "获取上级菜单数组")
    public ResultObject<List<String>> superior(@ApiParam(value = "菜单id") @RequestParam("id") String id) {
        //先获取全量菜单数据
        List<MenuTreeVO> menuTreeVOList = menuService.getList(null);
        //再通过菜单id查找所有上级菜单
        List<String> list = menuService.getFatherTree(menuTreeVOList, id);

        //如果有查到上级菜单，则list第一条数据为该菜单本身 去掉
        if (list.size() > 0) list.remove(0);

        return ResultObject.success(list);
    }

    @PostMapping("/save")
    @ApiOperation(value = "保存菜单信息")
    public ResultObject save(@RequestBody Menu menu) {
        logger.info("请求参数："+menu.toString());
        menu = (Menu) FillUtil.fill(menu);
        logger.info("填充后的信息："+menu.toString());
        boolean flag = menuService.saveOrUpdate(menu);
        if (flag) return ResultObject.success("保存成功");
        else return ResultObject.fail("保存失败");
    }

    @GetMapping("/delete")
    @ApiOperation(value = "根据id删除菜单信息")
    public ResultObject deleteById(@ApiParam(value = "菜单id") @RequestParam("id") String id) {
        logger.info("删除菜单信息id："+id);
        return menuService.deleteById(id);
    }


    @GetMapping("/getMenu")
    @ApiOperation(value = "根据角色id获取菜单信息")
    public ResultObject<List<UserMenuTreeVO>> getMenu(@ApiParam(value = "角色id") @RequestParam("roleId") String roleId) {
        logger.info("角色id："+roleId);
        return ResultObject.success(menuService.queryByRoleId(roleId));
    }


}
